import { reactive, toRefs, watch, Ref } from 'vue'
import { useRouter } from 'vue-router'
import { FormInst } from 'naive-ui'
import { useApi } from '@/api'
import { LoginResponse } from '@global/types'
import useUserInfo from '@/store/useUserInfo'

type Props = {
  formRef: Ref<FormInst>
}

export default ({ formRef }: Props) => {
  const $router = useRouter()
  const api = useApi()

  const state = reactive({
    /** 模式： 注册 | 密码登录 | 短信登录 */
    mode: 'loginPsd' as 'register' | 'loginPsd' | 'loginSms',
    /** 表单 */
    form: {
      name: '',
      phone: '',
      psd: '',
      code: ''
    }
  })
  // 监听 mode，重置表单和错误提示
  watch(
    () => state.mode,
    () => {
      state.form = {
        name: '',
        phone: '',
        psd: '',
        code: ''
      }
    }
  )

  const loginHandler = async () => {
    await formRef.value.validate(err => new Promise((resolve, reject) => (err ? reject(err) : resolve(1))))
    let userInfo = {} as LoginResponse
    if (state.mode === 'loginPsd') userInfo = await api.post('/user/login_psd', state.form) // 密码登录请求
    if (state.mode === 'loginSms') userInfo = await api.post('/user/login_sms', state.form) // 短信登录请求
    useUserInfo().$patch(userInfo)
    $router.push('/') // 跳转到主页
  }

  const registerHandler = async () => {
    await formRef.value.validate(err => new Promise((resolve, reject) => (err ? reject(err) : resolve(1))))
    await api.post('/user/register', state.form) // 发起注册请求
    const phone = state.form.phone
    state.mode = 'loginPsd' // 改为登录密码模式
    state.form.phone = phone
  }

  return {
    ...toRefs(state),
    /** 登录 */
    loginHandler,
    /** 注册 */
    registerHandler
  }
}
